var Data01=[];
var Data02=[];
var Data03=[];
var DataERP=[];  //用于接收存放ERP手工录入各种仪表用量
var millName; //染厂名称
var millData = [];
var millData01 = [];
var openID; // 微信ID
var millPort; // 染厂对应的端口号
var hgS2;
var Judge_plan;
var code = getQueryString("code");

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}



$(function () {
    /*设置日期默认值*/
    var etime = new Date();
    $('#appDateTime').val(formatterSDate(etime));
    $('#appDateTime02').val(formatterEDate(etime));

    /******************************************/

   //获取登录用户的权限和对应显示的数据
    getopenid()


    /**********************************************************/
});

function getopenid() {
    console.log('https://www.xdfznh.club/wxpadbe/switch/oao/' + code);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/switch/oao/'
            + code,
        type: 'get',
        dataType: 'json',
        // 成功回调
        success: function (data) {
            console.log('请求成功');
            openID = data.data;
            console.log('openID=' + openID);
            getmill();
        },
        //失败回调
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //查看错误信息
            console.log('失败回调');
            console.log(XMLHttpRequest.status);
            console.log(XMLHttpRequest.readyState);
            console.log(textStatus);
        }
    })
}

//获取微信号对应的染厂名称
function getmill() {
    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/userMillController/selectMills/'
            + openID,

        type: 'get',
        dataType: 'json',
        success: function (data) {
            console.log(data.length);
            var ID;
            var liNodes = document.getElementsByTagName("input");
            if (data.length == 0) {
                // 关闭当前页面
                alert('当前用户没有权限！');


            }

            if (data.length > 0) {
                millName = data[0].mill;  //取第一行的染厂名称为默认
                millPort = data[0].port_erp;  // 取当前染厂名称对应的端口号
                millData01=data;  // 把整个获取到的数组备份一份

                for (var n = 0; n < data.length; n++) {
                    millData[n] = data[n].mill;
                    console.log(data[n].mill);
                }
                ;
                getJurisdiction(); //获取个人查看报表的权限
                getDropDownDate(); // 设置下拉

            };
        }
    })
};

//获取个人查看报表的权限
function getJurisdiction() {
    console.log('https://www.xdfznh.club/wxpadbe'
        + '/perm/selectBoss/'
        + openID + '/'
        + millName);
    console.log(millName);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/perm/selectBoss/'
            + openID + '/'
            + millName,

        type: 'get',
        dataType: 'json',
        success: function (data) {

            if (data.length > 0) {
                millName = data[0].mill;
                var plan = eval('(' + data[0].auth_energy + ')');

                if (plan) {
                    Judge_plan = true;
                    getDataERP();
                    getData();
                    //showColor();
                    getsum();
                } else {
                    Judge_plan = false;
                    alert('当前用户没有查看能源权限！');

                }


                for (var n = 0; n < data.length; n++) {
                    millData[n] = data[n].mill;
                    console.log(data[n].mill);
                };

                getDropDownDate(); // 设置下拉

            } else {
                Judge_plan = false;
                alert('当前用户没有查看报表权限！');

            };
        }
    })

};


function getData() {

    var data1=document.getElementById("appDateTime").value.substr(0, 10);
    var data2=document.getElementById("appDateTime02").value.substr(0, 10);

    if (timeFn(data1,data2)>31){
        alert('当前查询日期区间大于一个月，不可查询！');
        return;
    }

Data01=[];
Data02=[];
Data03=[];

console.log('https://www.xdfznh.club/wxpadbe/execute/llj/'
    + millName
    + "/call getYBConsumption('"
    + document.getElementById("appDateTime").value
    + "','"
    + document.getElementById("appDateTime02").value
    + "')");

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/execute/llj/'
            + millName
            + "/call getYBConsumption('"
            + document.getElementById("appDateTime").value
            + "','"
            + document.getElementById("appDateTime02").value
            + "')",

        type: 'get',
        dataType: 'json',
        success: function (data) {
            Data01=data;
            console.log(2);
            console.log(Data01);
           // getDataERP();
            getData02();

        },
        complete: function(XMLHttpRequest, textStatus) {
            $(".buttom").attr("disabled",false);
        }
    });

};

function getData02() {
    console.log(3);
    $.ajax({
        url:'https://www.xdfznh.club/wxpadbe/execute/query/'
            + millName + '/'
            + "call p_GetJTHyield('"
            + document.getElementById("appDateTime").value
            +"','"
            + document.getElementById("appDateTime02").value
            + "')",

        type: 'get',
        dataType: 'json',
        success: function (data) {
            Data02 = data;
            console.log(4);
            console.log(Data02);
            MergeArrays();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //查看错误信息
            console.log('失败回调');
            MergeArrays();
        },
        complete: function(XMLHttpRequest, textStatus) {
            $(".buttom").attr("disabled",false);
        }
    });

    console.log('https://www.xdfznh.club/wxpadbe/execute/query/'
        + millName + '/'
        + "call p_GetJTHyield('"
        + document.getElementById("appDateTime").value
        +"','"
        + document.getElementById("appDateTime02").value
        + "')");

};

function getDataERP() {
    DataERP=[];
    var data1=document.getElementById("appDateTime").value.substr(0, 10);
    var data2=document.getElementById("appDateTime02").value.substr(0, 10);

    console.log('https://www.xdfznh.club/wxpadbe/execute/query/'
        + millName + '/'
        + "call getYBERPconsumption('"
        + data1
        +"','"
        + data2
        + "')");

    $.ajax({
        url:'https://www.xdfznh.club/wxpadbe/execute/query/'
            + millName + '/'
            + "call getYBERPconsumption('"
            + data1
            +"','"
            + data2
            + "')",

        type: 'get',
        dataType: 'json',
        success: function (data) {
            DataERP = data;
            console.log(DataERP);
            //getsum();
        },
    });
};

/*合并数组*/
function MergeArrays() {
    console.log(5);
    if (Data01.length > 0) {
        Data01.map(function (val) {
            Data02.map(function (val2) {
                if (val.B_YBName === val2.B_JTH) {
                    return Object.assign(val, val2)
                }
            })
        });

       console.log(Data01);
       //console.log(Data01[0].B_Qty);

        Data01.forEach(function (val) {
            Data03.push({
                b_YBName: val.B_YBName,
                b_YBType: val.B_YBType,
                b_LLAll: val.B_LLAll,
                B_Qty: Number(val.B_Qty)>0 ? val.B_Qty : '',
                XH: Number(val.B_Qty) >0 ? (parseFloat(val.B_LLAll) / parseFloat(val.B_Qty) * 1000).toFixed(1) :''

            })
        });
        getgrid(Data03);
        console.log(Data03);
        console.log(6);
        //getsum();
    }
}

function getgrid(data) {
    var data1;
    var data2;
    var data3;
    var data4;

    emptygrid();

    data1=data.filter(item=>item.b_YBType==='天然气');
    data2=data.filter(item=>item.b_YBType==='水表');
    data3=data.filter(item=>item.b_YBType==='电表');
    data4=data.filter(item=>item.b_YBType==='蒸汽');

    $('#waterdetai01').datagrid('loadData', data1);
    $('#waterdetai02').datagrid('loadData', data2);
    $('#waterdetai03').datagrid('loadData', data3);
    $('#waterdetai04').datagrid('loadData', data4);

}

/*清空报表数据*/
function emptygrid() {
    var data7=[];
    $('#waterdetai01').datagrid('loadData', data7);
    $('#waterdetai02').datagrid('loadData', data7);
    $('#waterdetai03').datagrid('loadData', data7);
    $('#waterdetai04').datagrid('loadData', data7);
}

function getsum() {

    $('#waterdetai01').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {
            data = data.rows;
            $(this).datagrid('reloadFooter', [{
                b_YBName: '总量',
                b_LLAll:  DataERP.length>0 ? DataERP[0].trq : '',
                //B_Qty: qty.toFixed(1),

            }])
        },
        onLoadError: function(none){
            $(this).datagrid('reloadFooter', [{
                b_YBName: '总量',
                b_LLAll: '',
            }])
        },
       rowStyler: function (index, row) {
        if (row.b_YBName=='合计') {
            //return 'color:#0080FF ';   //#E0ECFF
            return 'background-color:#E0ECFF';
            //return 'background-color:#0000C6;color:#fff;font-weight:bold;';
        }
    }
  });

    $('#waterdetai02').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {

            $(this).datagrid('reloadFooter', [{
                b_YBName: '总量',
                b_LLAll: DataERP.length>0? DataERP[0].water:'',

            }])
        },
        rowStyler: function (index, row) {
            if (row.b_YBName=='合计') {
                //return 'color:#0080FF ';   //#E0ECFF
                return 'background-color:#E0ECFF';
                //return 'background-color:#0000C6;color:#fff;font-weight:bold;';
            }
        }
    });

    $('#waterdetai03').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {

            $(this).datagrid('reloadFooter', [{
                b_YBName: '总量',
                b_LLAll: DataERP.length>0 ? DataERP[0].db:'',

            }])
        },
        rowStyler: function (index, row) {
            if (row.b_YBName=='合计') {
                //return 'color:#0080FF ';   //#E0ECFF
                return 'background-color:#E0ECFF';
                //return 'background-color:#0000C6;color:#fff;font-weight:bold;';
            }
        }
    });

    $('#waterdetai04').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {
           /* data = data.rows;
            var total = 0;
            var qty=0;
            var xh=0;
            for (let i = 0; i < data.length; i++) {
                total += data[i].b_LLAll ? parseFloat(data[i].b_LLAll) : 0;
                qty += data[i].B_Qty ? parseFloat(data[i].B_Qty) : 0;
                xh += data[i].XH ? parseFloat(data[i].XH) : 0;
            }
            */

            $(this).datagrid('reloadFooter', [{
                b_YBName: '总量',
                b_LLAll: DataERP.length>0 ?DataERP[0].zq :'',

            }])
        },
        rowStyler: function (index, row) {
            if (row.b_YBName=='合计') {
                //return 'color:#0080FF ';   //#E0ECFF
                return 'background-color:#E0ECFF';
                //return 'background-color:#0000C6;color:#fff;font-weight:bold;';
            }
        }
    })
};

//查询事件
function getquery() {
    if (Judge_plan == true) {
        getDataERP();
        getData();
        getsum();
    }
}

/******************************************************************************************/

/*设置时间格式*/
function add0(m) {
    return m < 10 ? '0' + m : m
}

function format(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

formatterSDate = function (date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    return date.getFullYear() + '-' + month + '-' + day + " " + "07" + ":" + "00";
};

formatterEDate = function (date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    var hor = date.getHours()> 9 ? date.getHours() : "0" + date.getHours();
    var min = date.getMinutes()> 9 ? date.getMinutes() : "0" + date.getMinutes();;
    var sec = date.getSeconds();
    return date.getFullYear() + '-' + month + '-' + day + " " + hor + ":" + "00";
};


/*****************************************************************************************/

/*自定义本月日期时间*/
customSDateMonth = function (date) {
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    return date.getFullYear() + '-' + month + '-' + "01" + " " + "07" + ":" + "00";
};

//计算当前日期的前后几天的日期
function getDay(day){
    var today = new Date();
    var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth();
    var tDate = today.getDate();
    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);
    return tYear+"-"+tMonth+"-"+tDate+ " " + "07" + ":" + "00";
}

function doHandleMonth(month){
    var m = month;
    if(month.toString().length == 1){
        m = "0" + month;
    }
    return m;
}

/*查询一天的日期设置*/
function getdaydate() {
    var etime = new Date();
    $('#appDateTime').val(getDay(-1));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}
/*查询一周的日期设置*/
function getWeekdate() {
    var etime =new Date();
    $('#appDateTime').val(getDay(-7));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}
/*查询一个月的日期设置*/
function getOneMonthdate() {
    var etime =new Date();
    $('#appDateTime').val(getDay(-30));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}

/*查询本月的日期设置*/
function getMonthdate() {
    var etime = new Date();
    $('#appDateTime').val(customSDateMonth(etime));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}


/********************************************************************************/
/*获取标签的序号*/
function getTabSelectedIndex() {
    return $('#tabs').tabs('getTabIndex', $('#tabs').tabs('getSelected'));
}

//获取当前所选中标签的序号，打开对应的图形信息
function getClientName() {
    if (Judge_plan == true) {
        var SDate = document.getElementById("appDateTime").value;
        var EDate = document.getElementById("appDateTime02").value;
        var strhref;
        switch (getTabSelectedIndex()) {
            case 0:
                strhref = "html/wx_image_detail.html"
                    + '?'
                    + 'SDate=' + SDate
                    + '&'
                    + 'EDate=' + EDate
                    + '&'
                    + 'ybname=' + '天然气'
                    + '&'
                    + 'millname=' + millName;

                location.href = strhref;
                // $("#imagedetable").attr("href",strhref);
                break;

            case 1:
                strhref = "html/wx_image_detail.html"
                    + '?'
                    + 'SDate=' + SDate
                    + '&'
                    + 'EDate=' + EDate
                    + '&'
                    + 'ybname=' + '水表'
                    + '&'
                    + 'millname=' + millName;

                location.href = strhref;
                // $("#imagedetable").attr("href",strhref);
                break;
            case 2:
                strhref = "html/wx_image_detail.html"
                    + '?'
                    + 'SDate=' + SDate
                    + '&'
                    + 'EDate=' + EDate
                    + '&'
                    + 'ybname=' + '电表'
                    + '&'
                    + 'millname=' + millName;

                location.href = strhref;
                //$("#imagedetable").attr("href",strhref);
                break;
            case 3:
                strhref = "html/wx_image_detail.html"
                    + '?'
                    + 'SDate=' + SDate
                    + '&'
                    + 'EDate=' + EDate
                    + '&'
                    + 'ybname=' + '蒸汽'
                    + '&'
                    + 'millname=' + millName;

                location.href = strhref;
                //$("#imagedetable").attr("href",strhref);
                break;
        }
    }

}

/*
$("#waterdetai01").datagrid({
    onClickRow:function(index, row){//鼠标双击事件
       console.log('双击事件')
    }
});
*/

//设置染厂下拉
function getDropDownDate() {
    console.log('2=' + millData);
    hgS2 = new selectSwiper({
        el: '.select_box2',
        mustSelect: true,
        activeIndex: 0,
        data: millData,
        init: function (index) {
            if (index !== -1) {
                $('.btn2').html(this.data[index]);
            }
        },
        okFunUndefind: function () {
            alert('必须选择一项');
        },
        okFun: function (index) {
            $('.btn2').html(this.data[index]);
            millName = $('button').text();
            millPort = millData01.filter(item=>item.mill===millName)[0].port_erp;
            getJurisdictionmill();

        },
        closeFun: function () {
            console.log('取消');
        },
    });

    $('.btn2').on('click', function () {
        hgS2.openSelectSwiper();

    });
}

//在更换染厂之后  重新刷新数据  并判断个人权限
function getJurisdictionmill() {
    console.log('https://www.xdfznh.club/wxpadbe'
        + '/perm/selectBoss/'
        + openID + '/'
        + millName);

    emptygrid();  //更换染厂名称之后先清空表格数据

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/perm/selectBoss/'
            + openID + '/'
            + millName,

        type: 'get',
        dataType: 'json',
        success: function (data) {

            if (data.length > 0) {
                var plan = eval('(' + data[0].auth_energy + ')');

                if (plan) {
                    Judge_plan = true;
                    getDataERP();
                    getData();
                    showColor();
                    getsum();
                } else {
                    Judge_plan = false;
                    alert('当前用户没有查看能源权限！');
                }

            } else {
                Judge_plan = false;
                alert('当前用户没有查看报表权限！');
            }
            ;
        }
    })

}


/********************************************************************************/
//获取标签下网格被选中的行的数据
function getJTHDetail() {
    var SDate = document.getElementById("appDateTime").value;
    var EDate = document.getElementById("appDateTime02").value;
    var jth;  /*机台号*/

    var selected1 = $('#waterdetai01').datagrid('getSelected');
    var selected2 = $('#waterdetai02').datagrid('getSelected');
    var selected3 = $('#waterdetai03').datagrid('getSelected');
    var selected4 = $('#waterdetai04').datagrid('getSelected');


    switch (getTabSelectedIndex()) {
        case 0:
            if (selected1 == undefined ) {
                //   未选择
                alert("未选择机台号，无法查询明细！");
                console.log(0);
                return;
            }
            jth=selected1.b_YBName;


            location.href = 'html/wx_main_detail.html'
                + '?jth=' + jth
                + '&'
                + 'millName=' + millName
                + '&'
                + 'SDate=' + SDate
                + '&'
                + 'EDate=' + EDate;
            break;

        case 1:
            if (selected2 == undefined ) {
                //   未选择
                alert("未选择机台号，无法查询明细！");
                console.log(0);
                return;
            }
            jth=selected2.b_YBName;


            location.href = 'html/wx_main_detail.html' + '?jth=' + jth
                + '&'
                + 'millName=' + millName
                + '&'
                + 'SDate=' + SDate
                + '&'
                + 'EDate=' + EDate;
            break;

        case 2:
            if (selected3 == undefined ) {
                //   未选择
                alert("未选择机台号，无法查询明细！");
                console.log(0);
                return;
            }
            jth=selected3.b_YBName;


            location.href = 'html/wx_main_detail.html' + '?jth=' + jth
                + '&'
                + 'millName=' + millName
                + '&'
                + 'SDate=' + SDate
                + '&'
                + 'EDate=' + EDate;
            break;

        case 3:
            if (selected4 == undefined ) {
                //   未选择
                alert("未选择机台号，无法查询明细！");
                console.log(0);
                return;
            }
            jth=selected4.b_YBName;


            location.href = 'html/wx_main_detail.html' + '?jth=' + jth
                + '&'
                + 'millName=' + millName
                + '&'
                + 'SDate=' + SDate
                + '&'
                + 'EDate=' + EDate;
            break;

    }

}

/*****************************************************************************/

/*计算两个时间差*/
function timeFn(d1,d2) {//di作为一个变量传进来
//如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
    var dateBegin = new Date(d1.replace(/-/g, "/"));//将-转化为/，使用new Date
    var dateEnd =  new Date(d2.replace(/-/g, "/"));//将-转化为/，使用new Date
    var dateDiff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数
    var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
    var leave1=dateDiff%(24*3600*1000) //计算天数后剩余的毫秒数
    var hours=Math.floor(leave1/(3600*1000))//计算出小时数
//计算相差分钟数
    var leave2=leave1%(3600*1000) //计算小时数后剩余的毫秒数
    var minutes=Math.floor(leave2/(60*1000))//计算相差分钟数
//计算相差秒数
    var leave3=leave2%(60*1000) //计算分钟数后剩余的毫秒数
    var seconds=Math.round(leave3/1000)
    //console.log(" 相差 "+dayDiff+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒")
    //console.log(dateDiff+"时间差的毫秒数",dayDiff+"计算出相差天数",leave1+"计算天数后剩余的毫秒数"
    //   ,hours+"计算出小时数",minutes+"计算相差分钟数",seconds+"计算相差秒数");

    return Math.abs(dayDiff);
}

function showColor() {

    //showcolor01();
    //showcolor02();
    //showcolor03();
    //showcolor04();


}

function showcolor01() {
    $('#waterdetai01').datagrid({
        rowStyler: function (index, row) {
            if (row.b_YBName=='合计') {
                //return 'color:#0080FF ';   //#E0ECFF
                return 'background-color:#E0ECFF';
                //return 'background-color:#0000C6;color:#fff;font-weight:bold;';
            }
        }
    });
}

function showcolor02() {
    $('#waterdetai02').datagrid({
        rowStyler: function (index, row) {
            if (row.b_YBName=='合计') {
                //return 'color:#0080FF ';   //#E0ECFF
                return 'background-color:#E0ECFF';
                //return 'background-color:#0000C6;color:#fff;font-weight:bold;';
            }
        }
    });
}

function showcolor03() {
    $('#waterdetai03').datagrid({
        rowStyler: function (index, row) {
            if (row.b_YBName=='合计') {
                //return 'color:#0080FF ';   //#E0ECFF
                return 'background-color:#E0ECFF';
                //return 'background-color:#0000C6;color:#fff;font-weight:bold;';
            }
        }
    });
}

function showcolor04() {
    $('#waterdetai04').datagrid({
        rowStyler: function (index, row) {
            if (row.b_YBName=='合计') {
                //return 'color:#0080FF ';   //#E0ECFF
                return 'background-color:#E0ECFF';
                //return 'background-color:#0000C6;color:#fff;font-weight:bold;';
            }
        }
    });
}